﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zhp.Common.Helper
{
    public static class ApplicationHelper
    {
        public static IApplicationBuilder ApplicationBuilder { get; set; }

        /// <summary>
        /// 获取全局服务
        /// </summary>
        /// <typeparam name="T">接口类型</typeparam>
        /// <returns></returns>
        public static T GetService<T>() where T : class
        {
            if (ApplicationBuilder == null)
            {
                return default(T);
            }
            return ApplicationBuilder.ApplicationServices.GetService(typeof(T)) as T;
        }

        /// <summary>
        /// 获取当前请求为生命周期的服务
        /// </summary>
        /// <typeparam name="T">接口类型</typeparam>
        /// <returns></returns>
        public static T GetScopeService<T>() where T : class
        {
            return (T)GetHttpContext()?.RequestServices.GetService(typeof(T));
        }

        /// <summary>
        /// 获取当前请求上下文
        /// </summary>
        /// <returns></returns>
        public static HttpContext GetHttpContext()
        {
            return GetService<IHttpContextAccessor>()?.HttpContext;
        }
    }
}
